package cn.lumora.core.security.rea;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.security.KeyPair;
import java.util.Base64;

/**
 * 密钥轮换定时任务，定期生成新的RSA密钥对
 */
@Component
@Slf4j
public class KeyRotationTask {

    private final RSAKeyGenerator rsaKeyGenerator;
    private final RSAKeyStorageService rsaKeyStorageService;

    public KeyRotationTask(RSAKeyGenerator rsaKeyGenerator,
                           RSAKeyStorageService rsaKeyStorageService) {
        this.rsaKeyGenerator = rsaKeyGenerator;
        this.rsaKeyStorageService = rsaKeyStorageService;
    }

    /**
     * 每24小时轮换一次密钥
     */
    @Scheduled(fixedRate = 86400000) // 24小时（毫秒）
    public void rotateKeys() {
        try {
            // 生成新的密钥对
            KeyPair keyPair = rsaKeyGenerator.generateKeyPair();

            // 将密钥对转换为Base64编码的字符串
            String publicKey = Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded());
            String privateKey = Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded());

            // 存储新密钥
            rsaKeyStorageService.storeKeyPair(publicKey, privateKey);

            log.info("RSA密钥成功轮换");
        } catch (Exception e) {
            log.error("密钥轮换失败,日志信息:{}", e.getMessage());
        }
    }
}
